#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description:       :               用来放一些有碍观瞻的小函数
@Date     :2022/05/10 01:46:41
@Author      :Cosecant
@version      :1.0
                    _ooOoo_                     
                   o8888888o                    
                  88   .   88                    
                   (| -_- |)                    
                   O\  =  /O                    
                ____/`---'\____                 
              .'   \|     |/   `.               
             /   \|||  :  |||/   \              
            /  _||||| -:- |||||_  \             
            |   | \ \  -  /// |   |             
            | \_|  ''\---/''  |_/ |             
            \  .-\__  `-`  ___/-. /             
          ___`. .'  /--.--\  `. . __            
       .'' '<  `.___\_<|>_/___.'  >' ''.         
      | | :  `- \`.;`\ _ /`;.`/ - ` : | |       
      \  \ `-.   \_ __\ /__ _/   .-` /  /       
 ======`-.____`-.___\_____/___.-`____.-'======   
                    `=---='                     
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   
        佛祖保佑        永无BUG                  
'''
import numpy as np
import torch

def save_checkpoint (state,file_name):
    """
    @description  :保存模型
    ---------
    @param  :   state-> model.state_dict()
    -------
    @Returns  :
    -------
    """
    torch.save(state,file_name)

def load_checkpoint(checkpoint, mymodel, myoptimizer):
    """
    @description  :加载保存的模型
    ---------
    @param  :   checkpoint->{'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}
                mymodel-> model对象
                myoptimizer-> optimizer对象
    -------
    @Returns  :
    -------
    """
    mymodel.load_state_dict(checkpoint['state_dict'])
    myoptimizer.load_state_dict(checkpoint['optimizer'])

if __name__ == '__main__':
  from pandas import DataFrame, pivot
  import scipy.io as sio
  import seaborn as sns; sns.set()
  import matplotlib.pyplot as plt
  import torch
  import torch.nn as nn

  """matData=sio.loadmat("./EMG_data/thumb_scaled/normalization/S1_E1_A1.mat")
  df=DataFrame(None,)
  emg_window_sum=[]
  foo=np.zeros((3,16))
  for i in range(16):
    sensor_num="emg_sensor"+str(i)
    for index in range(len(matData['emg'][:,i]))
    emg_window_sum.append(matData['emg'][:,i])
    for j in range(3):
      glove_num="glove_sensor"+str(j)

      data=DataFrame({sensor_num:matData['emg'][:,i],glove_num:matData['glove'][:,0]})
      spearman=data.corr(method='spearman')#计算spearman相关系数
      foo[j,i]=spearman.loc[glove_num,sensor_num]
  print(foo)
  df=DataFrame() """
  from statsmodels.tsa.stattools import grangercausalitytests
  matData=sio.loadmat("./EMG_data/thumb_scaled/normalization/S1_E1_A2.mat")

  sensor_list=[]
  glove_list=[]
  for i in range(16):
    sensor_num="emg_sensor"+str(i)
    sensor_list.append(sensor_num)
  for i in range(3):
    sensor_num="glove_sensor"+str(i)
    glove_list.append(sensor_num) 

  matData['emg']=matData['emg']-np.mean(matData['emg'], axis=0)
  matData['emg']=np.maximum(matData['emg'],-matData['emg'])

  print(matData['emg'].shape)
  pool1d=nn.MaxPool1d(kernel_size=101,stride=1,padding=50)
  output=pool1d(torch.from_numpy(matData['emg']).unsqueeze(0).permute(0,2,1))
  output=output.squeeze().permute(1,0)
  output=output.detach().numpy()
  plt.plot(output[:,0])
  plt.show() 
  print(output.shape)
  #maxlag=[10]
  foo=np.ones((3,16))
  for i in range(16):
    for j in range(3):
      df=[]
      df.append(np.array(matData['glove'][:,j]))
      df.append(np.array( output[:,i]))
      df=np.array(df).T
      bar=grangercausalitytests(df, maxlag=[10])
      foo[j,i]=bar[10][0]["ssr_ftest"][1]
      """  for k in range(20):
        if(foo[j,i]>bar[k+1][0]["ssr_ftest"][1]):
          foo[j,i]=bar[k+1][0]["ssr_ftest"][1]"""
  dataframe=DataFrame(foo,glove_list,sensor_list)
  #dataframe.pivot(index='glove_sensors',columns='emg_sensors',values='P-Values')
  sns.heatmap(data=dataframe,annot=True,fmt='.3f')
  plt.show()
  print(dataframe)
  #print(grangercausalitytests(df, maxlag=50))